import { useSetState } from 'ahooks'
import { Modal, ModalProps } from 'antd'
import React, { useRef } from 'react'
import type { DraggableData, DraggableEvent } from 'react-draggable'
import Draggable from 'react-draggable'

export interface State {
  disabled: boolean
  bounds: { left: number; top: number; bottom: number; right: number }
}
/**
 * 拖拽弹窗
 */
const DragModal: React.FC<ModalProps> = ({ title, ...rest }) => {
  const [state, setState] = useSetState<State>({
    bounds: { left: 0, top: 0, bottom: 0, right: 0 },
    disabled: true
  })
  const draggleRef = useRef<HTMLDivElement>(null!)
  const handleMouseOver = () => {
    if (state.disabled) {
      setState({
        disabled: false
      })
    }
  }
  const handleMouseOut = () => {
    setState({
      disabled: true
    })
  }
  /**
   * 拖拽
   * @param _event
   * @param uiData
   */
  const onStart = (_event: DraggableEvent, uiData: DraggableData) => {
    const { clientWidth, clientHeight } = window.document.documentElement
    const targetRect = draggleRef.current?.getBoundingClientRect()
    if (!targetRect) return
    setState({
      bounds: {
        left: -targetRect.left + uiData.x,
        right: clientWidth - (targetRect.right - uiData.x),
        top: -targetRect.top + uiData.y,
        bottom: clientHeight - (targetRect.bottom - uiData.y)
      }
    })
  }
  return (
    <>
      <Modal
        title={
          <div style={{ width: '100%', cursor: 'move' }} onMouseOver={handleMouseOver} onMouseOut={handleMouseOut}>
            {title}
          </div>
        }
        mask={true}
        maskClosable={false} // 点击蒙层关闭
        {...rest}
        modalRender={(modal) => (
          <Draggable
            disabled={state.disabled}
            bounds={state.bounds}
            nodeRef={draggleRef}
            onStart={(event, uiData) => onStart(event, uiData)}
          >
            <div ref={draggleRef}>{modal}</div>
          </Draggable>
        )}
      />
    </>
  )
}
export default DragModal
